/**
 * Created by Administrator on 2016/10/5.
 */
var index = (function($){
    return{

        tableObj : null,
        otherElem : {},
        watchingOrderId : null,// 正查看的 订单id（打开了 订单详情模态框）
        deleteOrderImg: null,// 取消订单 上传图片凭证
        voucher: null,// 已取消的订单，查看模态框 数据

        // 初始化
        init: function(){
            momo.initPage();// 左边菜单栏
            //momo.download.call(this, "RushBuy/recordDownload");// 导出
            this.addBtnEvent();// 给“搜索”“重置”按钮添加点击事件

            this.initTable( {}, false );// 初始化表格

            // 导出
            this.otherElem = { };
        },

        // 初始化表格
        initTable: function( data, isIFrame ){
            console.log(data);
            var _self = this;

            var url = 'RushBuy/adminList';
            var editUrl = '';
            var colName = ['序号','管理员账号','创建时间','上次登录时间','操作'];
            var colModal = [
                { index: 'id', width:10, textOverflowEllipsis: true, sort: false, formatter: setNum},
                { index: 'username', width:15, textOverflowEllipsis: true, sort: false },
                { index: 'add_time', width:15, textOverflowEllipsis: true, sort: false },
                { index: 'last_login_time', width:15, textOverflowEllipsis:true, sort: false },
                { index: 'id', width:30, textOverflowEllipsis: true, sort: false, formatter: setOperate.bind(_self) },// 传入id，操作表单
            ];

            var _data = {};
            if( data != undefined ) _data = $.extend( _data, data );
            this.tableObj = new $.jqGrid( $('#jqGrid'), url, _data, colName, colModal, undefined, false, true, editUrl );
             console.log(this.tableObj);


            // （辅助函数）设置序号
            function setNum( val, rowData, index ) {
                var _num = ( _self.tableObj.currentPage - 1 ) *  _self.tableObj.data.page_size + ( index + 1 );
                return '<span>' + parseInt( _num ) + '</span>';
            }  
            // （辅助函数）设置操作（this是 lottery对象）
            function setOperate( val, rowData ){

                var _str =  '<a class="updateItem btn btn-mini btn-primary tableInnerBtn" onclick="index.edit(' + val + ',\''+rowData.username+'\',\''+rowData.remark+'\');">编辑</a>';
                 _str +=  '<a class="updateItem btn btn-mini btn-primary tableInnerBtn" onclick="index.del(\'' + val + '\');">删除</a>';
                 _str +=  '<a class="updateItem btn btn-mini btn-primary tableInnerBtn" onclick="index.reset(\'' + val + '\');">重置密码</a>';

                return _str;
            }
        },

        edit: function(id,username, remark){
            var message = $("#editModal").text();
                bootbox.dialog({
                    title: "新增",
                    message: message,
                    onEscape: function () {
                    }
                });
            $("#username").val(username);
            $("#remark").val(remark);
            $("#rush_admin_id").val(id);
        },

        reset:function(id){
            if(confirm("密码将被重置为123456，是否继续？")){
                momo.sendPost({"id":id}, 'RushBuy/ResetAdmin', function(data){
                    if(data.errcode == 0){
                        alert('操作成功');
                    }else{
                        alert(data.errmsg);
                    }
                }, function(){
                    alert('系统出错');
                })
            }
        },

        del:function(id){
            if(confirm("确认删除？")){
                var _data = {
                    "id":id
                }
                momo.sendPost(_data, 'RushBuy/delAdmin', function(data){
                    if(data.errcode){
                        alert(data.errmsg);
                    }else{
                        alert('操作成功');
                        window.location.href = 'adminList.html';
                    }
                },function(){
                    alert('删除失败！');
                })
            }
        },

        import:function(id){
            var message = $("#addModal").text();
          //  console.log(message);
            bootbox.dialog({
                    //size: 'large',
                    title: "导入优惠码",
                    message: message,
                    onEscape: function () {
                    }
                });
            $("#import_rush_id").val(id);
        },

        view:function(id){
            window.location.href = 'view.html?id='+id;
        },
     
        // 给“搜索”“重置”按钮、“展开/收起日志”、“取消订单”按钮、订单备注编辑、保存、取消按钮 添加点击事件
        addBtnEvent: function(){

            var _self = this;

            // 点击搜索按钮
            $('.searchBtn').click( function(){

                var _searchInput = $('#searchInput').val();
                // var _searchType = $('#searchType').val();
                // var _searchDay = $('#searchDay').val();
                // var _searchProvince = $('#searchProvince').val();
                // var _searchCity = $('#searchCity').val();

                var _timeArr = $('#searchTime').val().split(' - ');
                var _startTime = _timeArr[0] ? _timeArr[0] : '';
                var _endTime = _timeArr[1] ? _timeArr[1] : '';
                //console.log( _timeArr );

                var _data = {
                    "keyword": _searchInput,
                    "start": _startTime,
                    "end": _endTime,
                };
                this.tableObj.reloadData( _data, true );

                this.otherElem = $.extend( this.otherElem, _data);// 导出功能

            }.bind( this ));

            // 点击重置按钮
            $('.resetBtn ').click( function(){

                var isIFrame = momo.getURLElement("isIFrame");// 是否是模态框

                // 输入框
                if( !isIFrame ){
                    $('#searchInput').val('');
                    $('#searchTime').val('');
                }
                $('#searchDay').val('');

                // 下拉列表
                $('#searchType').val('0');// 订单类型
                $('#searchProvince').val('');

                $('.searchBtn').trigger('click');// 查询
            });

            $(document).on('click', '.newOne', function(){
                var message = $("#addModal").text();
                bootbox.dialog({
                    title: "新增",
                    message: message,
                    onEscape: function () {
                    }
                });
            })

            //新增用户
            $(document).on('click', '.addAdmin', function(){
                var username = $("#username").val();
                var password = $("#password").val();
                var confirm_pass = $("#confirm_password").val();

                if(username == ''){
                    alert("请输入用户名");
                    return false;
                }
                if(username.length > 20){
                    alert('用户名过长');
                    return false;
                }
                if (password == '') {
                    alert("请输入密码");
                    return false;
                }
                if (password.length > 16) {
                    alert("密码不能超过16个字符");
                    return false;
                }
                if (confirm_pass == '') {
                    alert("请输入确认密码");
                    return false;
                }

                if (password != confirm_pass) {
                    alert("密码与确认密码不一致");
                    return false;
                }
                var _data = {
                    'username': username,
                    'password': password,
                    'confirm_password' : confirm_pass,
                //    'remark': remark
                }
                momo.sendPost(_data, 'RushBuy/addAdmin', function(data){
                    if (data.errcode == 0) {
                        alert('操作成功');
                        bootbox.hideAll();
                        window.location.href = 'adminList.html';
                    }else{
                        alert(data.errmsg);
                    }
                },function(){
                    alert('操作失败');
                });
               
            });

            $(document).on('click', '.saveAdmin', function(){
                var password = $("#old_password").val();
                var new_password = $("#new_password").val();
                var confirm_pass = $("#confirm_password").val();
                var id = $("#rush_admin_id").val();
                if (password == '') {
                    alert("请输入旧密码");
                    return false;
                }
                
                if (new_password == '') {
                    alert("请输入新密码");
                    return false;
                }
                if (confirm_pass == '') {
                    alert("请输入确认密码");
                    return false;
                }
                if (new_password.length > 16) {
                    alert("新密码不能超过16个字符");
                    return false;
                }
                if (new_password != confirm_pass) {
                    alert("密码与确认密码不一致");
                    return false;
                }
                if (id == '') {
                    alert("更新参数出错");
                    return false;
                }
                var _data = {
                    'password': password,
                    'new_password':new_password,
                    'confirm_password' : confirm_pass,
                    'id':id
                }
                momo.sendPost(_data, 'RushBuy/saveAdmin', function(data){
                    if (data.errcode == 0) {
                        alert('操作成功');
                        bootbox.hideAll();
                        window.location.href = 'adminList.html';
                    }else{
                        alert(data.errmsg);
                    }
                },function(){
                    alert('操作失败');
                });
               
            });
        },
    }
})(jQuery);

var init = index.init.bind( index );
